<template>
  <base-modal :width="modAlProps.width" :isVisible="props.isVisible" :title="modAlProps.title" :buttons="buttons"
    @handleOk="buttonMessage" @handleCancle="handleCancle" class="site_modal">
    <template v-slot:body>
      <div>
        <a-form name="advanced_search" autoComplete="off" class="ant-advanced-search-form" :model="formState"
          ref="contentPushFrom">
          <a-form-item label="推送方式：" :rules="[{
            required: true,
          }]">
            <a-radio-group v-model:value="collectType">
              <a-radio value="1">复制型推送</a-radio>
              <a-radio value="3">镜像引用型推送</a-radio>
              <a-radio value="2">链接引用型推送</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item :label="'站点密码验证：'" :name="['secret', 'value']" :rules="[formState.secret.rule]">
            <a-input v-model:value="formState.secret.value" placeholder="请输入站点密码验证"></a-input>
          </a-form-item>
          <a-form-item :label="'目标站点'" :name="['siteId', 'value']" :rules="[formState.siteId.rule]">
            <a-select v-model:value="formState.siteId.value" @select="siteChange" placeholder="请选择" :options="siteOptions"
              :fieldNames="{
                label: 'siteName',
                value: 'id',
              }
                "></a-select>
          </a-form-item>
          <a-form-item :label="'文章推送状态'" :name="['pushType', 'value']" :rules="[formState.pushType.rule]">
            <a-select v-model:value="formState.pushType.value" placeholder="请选择" :options="pushTypeOptions"></a-select>
          </a-form-item>
          <a-form-item :label="'选择栏目'" v-if="gData && gData.length > 0">
            <a-input v-model:value="searchValue" placeholder="搜索栏目名称" style="height: 32px;">
              <template #suffix>
                <i class="iconfont icon-search"></i>
              </template>
            </a-input>
          </a-form-item>
          <a-form-item :label="''" v-if="gData && gData.length > 0">
            <div class="openorclose" @click="openorclose" v-show="isOpen">
              <a>全部收起</a>
              <i class="iconfont icon-up" style="font-size: 24px"> </i>
            </div>
            <div class="openorclose" @click="openorclose" v-show="!isOpen">
              <a>全部展开</a>
              <i class="iconfont icon-down" style="font-size: 24px"> </i>
            </div>
            <a-tree :expanded-keys="expandedKeys" :auto-expand-parent="autoExpandParent" :tree-data="gData"
              @expand="onExpand" :fieldNames="fieldNames" class="atree" @check="checkColumn" checkStrictly="true"
              v-model:checkedKeys="checkedKeys" v-if="gData.length" :height="300" checkable :selectable="false">
              <template #title="record">
                <!-- <span>{{ record.id }}</span> -->
                <span v-if="record.channelName.indexOf(searchValue) > -1">
                  {{ record.channelName.substr(0, record.channelName.indexOf(searchValue)) }}
                  <span style="color: #f50">{{ searchValue }}</span>
                  {{
                    record.channelName.substr(
                      record.channelName.indexOf(searchValue) + searchValue.length
                    )
                  }}
                </span>
                <span v-else>{{ record.channelName }}</span>
              </template>
            </a-tree>
          </a-form-item>
        </a-form>
      </div>
    </template>
  </base-modal>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick, onMounted, defineComponent, watch } from "vue";
import baseModal from "@/components/modal/baseModal.vue";
import { dataSourceType, detailDataItemType } from "@/type";
import request from "@/api/index";
import { Modal, message } from "ant-design-vue";
import type { TreeProps } from "ant-design-vue";
import getters from "@/store/getters";
//rule
const checkForm = async (
  _rule: dataSourceType = {},
  value: any
) => {
  if (_rule.required) {
    // 必填项验证非空并排除非必须项
    if (value == '' || value == undefined) {
      return Promise.reject(`${_rule.msg1}`);
    } else {
      return Promise.resolve();
    }
  }
};
//interface
interface Options {
  [propName: string | number]: any;
}
const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false,
  },
  contentIds: {
    type: Array,
    default: [],
  },
  disableCheckbox: {
    type: Number,
    default: null,
  },
});
//data
//模态框数据
const modAlProps = reactive<Options>({
  width: "M",
  title: "推送至",
});
//树结构数据
const fieldNames = reactive<dataSourceType>({
  title: "channelName",
  key: "id",
});
const contentPushFrom = ref();
const formState = ref<dataSourceType>({
  secret: {
    value: '',
    rule: {
      required: true,
      validator: checkForm,
      msg1: '请输入站点密码！',
      trigger: ["change", "blur"],
    },
  },
  siteId: {
    value: undefined,
    rule: {
      required: true,
      validator: checkForm,
      msg1: '请选择站点！',
      trigger: ["change", "blur"],
    },
  },
  pushType: {
    value: 1,
    rule: {
      required: false,
      validator: checkForm,
      msg1: '请选择文章推送状态！',
      trigger: ["change", "blur"],
    },
  }
});
//模态框button按钮个数和文案修改

let buttons = ref<Options[]>([
  {
    text: "推送",
    "html-type": "submit",
  },
  {
    text: "推送后继续",
    "html-type": "submit",
  },
]);
const siteOptions = ref<dataSourceType[]>([]);
const pushTypeOptions = ref<dataSourceType[]>([
  { label: '继承原文章状态', value: 1 },
  { label: '草稿', value: 2 },
]);
const secret = ref<any>('');
const siteId = ref<any[]>([]);
const userInfo = getters.userInfo();
const expandedKeys = ref<(string | number)[]>([]);
const searchValue = ref<string>("");
const autoExpandParent = ref<boolean>(true);
const gData = ref<dataSourceType[]>([]);
const dataList: TreeProps["treeData"] = [];
const isOpen = ref<boolean>(true); //是否展开或收起.
const channelId = ref<number | string>();
const collectType = ref<number | string>('1');
const checkedKeys = ref<dataSourceType>({ checked: [] });
const onExpand = (keys: string[]) => {
  expandedKeys.value = keys;
  autoExpandParent.value = false;
};
const gDataChange = ref<number>(1);
//watch
watch(searchValue, (value) => {
  parentKey.value = [];
  if (value) {
    dataList.map((item: any) => {
      getParentKey(value, item);
    });
  }
  expandedKeys.value = parentKey.value;
  searchValue.value = value;
  autoExpandParent.value = true;
});
const parentKey = ref<(string | number)[]>([]);
const getParentKey = (value: string | number, node: any) => {
  if (node.channelName.indexOf(value) > -1) {
    // parentKey = node.id;
    parentKey.value.push(node.id);
    if (node.children) {
      node.children.map((item: any) => {
        getParentKey(value, item);
      });
    }
  } else {
    if (node.children) {
      node.children.map((item: any) => {
        getParentKey(value, item);
      });
    }
  }
};

//获取站点层级树列表
const fetchSiteTreeList = async () => {
  const data: {} = {
    // orgId: userInfo.orgId,
    userId: userInfo.userId,
    allPermissions: true,
    isPushOpen: true,
  };
  siteOptions.value = await request.fetchContentSiteList(data);

  // fetchChannelChannelTree();
};
// 选择站点
const siteChange = async (val: any) => {
  fetchChannelListBySiteId(val);
};
//获取栏目层级树列表
const fetchChannelListBySiteId = async (val: any) => {
  let params = {
    allPermFilter: true,
    siteId: val,
  };
  let data = await request.fetchChannelListBySiteId(params);

  nextTick(() => {
    gData.value = data;
    loop(gData.value)
    dataList.push(...data);
    traversal(dataList);
  })
};
const openorclose = () => {
  isOpen.value = !isOpen.value;
  if (!isOpen.value) {
    expandedKeys.value = [];
  } else {
    traversal(dataList);
  }
};
const traversal = (data: any) => {
  data.map((item: any) => {
    parentKey.value.push(item.id);
    if (item.children) {
      traversal(item.children);
    }
  });
  expandedKeys.value = parentKey.value;
};
// 推送调取接口
const buttonMessage = async (msg: dataSourceType) => {
  let params = {
    ids: props.contentIds,
    statusSetup: formState.value.pushType.value,
    collectType: collectType.value,
    contentSitePushes: [
      {
        channelIds: checkedKeys.value.checked || [],
        secret: formState.value.secret.value,
        siteId: formState.value.siteId.value
      }
    ],
  };
  contentPushFrom.value
    .validate()
    .then(() => {
      if (!checkedKeys.value.checked.length) {
        message.error('请选择栏目！')
        return
      }
      request
        .fetchContentPush(params)
        .then((res: any) => {
          if (res.code == "00000 00000") {
            handleOk(msg);
            message.success(res.message);
            if (msg.text == "推送后继续") {
              formState.value.secret.value = '';
              formState.value.siteId.value = undefined;
            }
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {
          throw new Error(err);
        });
    })

};
const emits = defineEmits(["handleOk", "handleCancle"]);
const handleOk = (msg: any) => {
  emits("handleOk", msg);
};
// 选择推送栏目
const checkColumn = (val: any) => {
  console.log(checkedKeys.value.checked, 'collectType')
}
const handleCancle = (e: MouseEvent) => {
  emits("handleCancle", e);
};
const loop = (data: dataSourceType[]) => {
  data.forEach((item: any) => {
    if(item.id == props.disableCheckbox) {
      item.disableCheckbox = true
    }
    if (item.children && item.children.length) {
      item.disableCheckbox = true;
      loop(item.children)
    }
  })
}
//onmounted
onMounted(async () => {
  fetchSiteTreeList();
});
</script>

<style lang="scss" scoped>
::v-deep(.ant-form-item-label) {
  width: 109px;
}

::v-deep(.atree) {
  margin-left: 80px;
}

.openorclose {
  margin-left: 80px !important;
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-left: 16px;
  font-size: 14px;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: #1f6ded;

  .iconfont {
    margin-left: 5px;
  }
}
</style>
